<template>
  <div class="min-h-screen bg-gray-50 ">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Header -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <h1 class="text-2xl font-bold text-gray-900">异常热工况识别（CTI计算与凸包分析）</h1>
            <span class="ml-4 text-sm text-gray-500">当前车辆: {{ currentVehicle?.id }}</span>
          </div>
          <div class="flex space-x-2">
            <el-button @click="$router.go(-1)">返回</el-button>
            <el-button type="primary" @click="showStepsModal = true">步骤指引</el-button>
            <el-button type="warning" @click="showBatchAnalysisModal = true">批量分析</el-button>
          </div>
        </div>
      </div>

      <!-- Anomaly Detection Result -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">异常判定结果</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div class="bg-gradient-to-r from-red-500 to-red-600 text-white p-4 rounded-lg">
            <div class="text-sm opacity-90">判定结果</div>
            <div class="text-lg font-bold animate-pulse">启动异常处理路径</div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-2">
              距离型临界热指标（CTI）
              <el-button type="text" size="small" @click="showCTIModal = true">计算依据</el-button>
            </div>
            <div class="text-xl font-bold text-red-600">{{ ctiValue }}</div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-2">SOC 最大跳变幅度</div>
            <div class="text-xl font-bold text-orange-600">3.5%</div>
            <div class="text-xs text-gray-400 mt-1">预设跳变阈值：2%→超过阈值 1.5%</div>
          </div>
        </div>
      </div>

      <!-- 3D Visualization -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-semibold text-gray-900">三维热工况空间可视化</h2>
          <div class="flex space-x-2">
            <el-button
                :type="visualStep === 'complete' ? 'primary' : 'default'"
                size="small"
                @click="visualStep = 'complete'"
            >
              完整视图
            </el-button>
            <el-button
                :type="visualStep === 'historical' ? 'primary' : 'default'"
                size="small"
                @click="visualStep = 'historical'"
            >
              步骤1：历史异常点
            </el-button>
            <el-button
                :type="visualStep === 'convex' ? 'primary' : 'default'"
                size="small"
                @click="visualStep = 'convex'"
            >
              步骤2：凸包边界
            </el-button>
            <el-button
                :type="visualStep === 'current' ? 'primary' : 'default'"
                size="small"
                @click="visualStep = 'current'"
            >
              步骤3：当前点定位
            </el-button>
          </div>
        </div>

        <div class="chart-container">
          <v-chart
              :option="threeDOption"
              class="w-full h-full"
              autoresize
          />
        </div>
      </div>

      <!-- SOC Jump Analysis -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">SOC 跳变分析</h2>
        <div class="h-64 mb-4">
          <v-chart :option="socJumpOption" class="w-full h-full" />
        </div>
        <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
          <div class="text-sm font-medium text-yellow-800 mb-2">跳变原因推测</div>
          <div class="text-sm text-yellow-700">
            可能因高温极化电压恢复导致 SOC 估算虚增（类似案例：2025-03-22 车辆 TSL-005）
          </div>
        </div>
      </div>

      <!-- Actions -->
      <div class="bg-white rounded-lg shadow-sm p-6">
        <el-button
            type="primary"
            size="large"
            :loading="isNavigating"
            @click="goToChargingPriority"
        >
          {{ isNavigating ? '正在同步异常数据...' : '前往充电调度优先级页' }}
        </el-button>
      </div>
    </div>

    <!-- Modals -->
    <TechnicalModal
        v-model="showStepsModal"
        title="步骤指引"
        :sections="stepsSection"
    />

    <TechnicalModal
        v-model="showCTIModal"
        title="CTI 计算依据"
        :sections="ctiSections"
    />

    <!-- Batch Analysis Modal -->
    <BatchAnalysisModal
        v-model="showBatchAnalysisModal"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores'
import TechnicalModal from '@/components/TechnicalModal.vue'
import BatchAnalysisModal from '@/components/BatchAnalysisModal.vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, ScatterChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  VisualMapComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { Scatter3DChart, Line3DChart } from 'echarts-gl/charts'
import { Grid3DComponent } from 'echarts-gl/components'
use([
  CanvasRenderer,
  LineChart,
  ScatterChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  Scatter3DChart,
  Line3DChart,
  Grid3DComponent
])

const router = useRouter()
const store = useAppStore()

const currentVehicle = computed(() => store.currentVehicle)
const visualStep = ref('complete')
const showStepsModal = ref(false)
const showCTIModal = ref(false)
const isNavigating = ref(false)
const showBatchAnalysisModal = ref(false)

const ctiValue = computed(() => {
  if (currentVehicle.value) {
    return store.calculateCTI(currentVehicle.value.thmVector)
  }
  return 0
})

const threeDOption = computed(() => {
  const currentPoint = currentVehicle.value?.thmVector || [0.5, 0.5, 0.5];

  // Generate more historical points for better visualization
  const generateHistoricalPoints = () => {
    const points = [];
    for (let i = 0; i < 20; i++) {
      points.push([
        Math.random() * 0.2 + 0.7, // x between 0.7-0.9
        Math.random() * 0.2 + 0.6, // y between 0.6-0.8
        Math.random() * 0.2 + 0.65, // z between 0.65-0.85
        `历史异常点 ${i+1}`
      ]);
    }
    return points;
  };

  // Generate convex hull points (simplified)
  const generateConvexHull = () => {
    return [
      [0.7, 0.6, 0.65],
      [0.9, 0.6, 0.65],
      [0.9, 0.8, 0.65],
      [0.7, 0.8, 0.65],
      [0.7, 0.6, 0.85],
      [0.9, 0.6, 0.85],
      [0.9, 0.8, 0.85],
      [0.7, 0.8, 0.85],
      [0.7, 0.6, 0.65] // Close the loop
    ];
  };

  const historicalPoints = generateHistoricalPoints();
  const convexHullPoints = generateConvexHull();

  const baseOption = {
    tooltip: {},
    grid3D: {
      viewControl: {
        autoRotate: true,
        autoRotateSpeed: 10,
        distance: 120,
        alpha: 40,
        beta: 70,
        rotateSensitivity: 1,
        zoomSensitivity: 1,
        panSensitivity: 1
      },
      light: {
        main: {
          intensity: 1.2,
          shadow: true,
          shadowQuality: 'high',
          alpha: 30,
          beta: 40
        },
        ambient: {
          intensity: 0.3
        }
      }
    },
    xAxis3D: {
      type: 'value',
      name: '温度',
      min: 0,
      max: 1,
      axisLine: { lineStyle: { color: '#999' } },
      axisLabel: { color: '#666' }
    },
    yAxis3D: {
      type: 'value',
      name: '放电时长',
      min: 0,
      max: 1,
      axisLine: { lineStyle: { color: '#999' } },
      axisLabel: { color: '#666' }
    },
    zAxis3D: {
      type: 'value',
      name: '放电功率',
      min: 0,
      max: 1,
      axisLine: { lineStyle: { color: '#999' } },
      axisLabel: { color: '#666' }
    },
    visualMap: {
      show: false,
      dimension: 2,
      min: 0,
      max: 1,
      inRange: {
        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
      }
    }
  };

  // Show different elements based on visualStep
  const series = [];

  if (visualStep.value === 'historical' || visualStep.value === 'complete') {
    series.push({
      type: 'scatter3D',
      name: '历史异常点',
      data: historicalPoints,
      symbolSize: 8,
      itemStyle: {
        color: '#ff4d4f',
        opacity: 0.8
      },
      emphasis: {
        itemStyle: {
          color: '#ff4d4f',
          opacity: 1
        }
      }
    });
  }

  if (visualStep.value === 'convex' || visualStep.value === 'complete') {
    series.push({
      type: 'line3D',
      name: '凸包边界',
      data: convexHullPoints,
      lineStyle: {
        width: 2,
        color: '#1890ff',
        opacity: 0.8
      },
      emphasis: {
        lineStyle: {
          opacity: 1
        }
      }
    });
  }

  if (visualStep.value === 'current' || visualStep.value === 'complete') {
    series.push({
      type: 'scatter3D',
      name: '当前点',
      data: [currentPoint],
      symbolSize: 16,
      itemStyle: {
        color: '#faad14',
        opacity: 1
      },
      emphasis: {
        itemStyle: {
          color: '#faad14',
          opacity: 1
        }
      },
      label: {
        show: true,
        formatter: '当前车辆',
        position: 'top',
        textStyle: {
          color: '#faad14',
          fontSize: 14,
          backgroundColor: 'rgba(0,0,0,0.7)',
          padding: [4, 8],
          borderRadius: 4
        }
      }
    });
  }

  return {
    ...baseOption,
    series
  };
});

const socJumpOption = computed(() => ({
  title: {
    text: 'SOC 跳变物理逻辑校验',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['SOC (%)', '电流 (A)'],
    bottom: 0
  },
  xAxis: {
    type: 'category',
    data: ['10:00', '10:05', '10:10', '10:15', '10:20', '10:25', '10:30']
  },
  yAxis: [
    {
      type: 'value',
      name: 'SOC (%)',
      position: 'left'
    },
    {
      type: 'value',
      name: '电流 (A)',
      position: 'right'
    }
  ],
  series: [
    {
      name: 'SOC (%)',
      type: 'line',
      data: [51.2, 49.8, 53.3, 52.1, 50.5, 49.2, 47.8],
      yAxisIndex: 0,
      itemStyle: { color: '#3b82f6' },
      markPoint: {
        data: [
          { coord: [2, 53.3], name: '异常跳变点', itemStyle: { color: '#ef4444' } }
        ]
      }
    },
    {
      name: '电流 (A)',
      type: 'line',
      data: [-10.2, -11.5, -11.8, -12.1, -12.0, -11.9, -12.3],
      yAxisIndex: 1,
      itemStyle: { color: '#ef4444' },
      markPoint: {
        data: [
          { coord: [2, -11.8], name: '对应电流值', itemStyle: { color: '#ef4444' } }
        ]
      }
    }
  ]
}))

const stepsSection = [
  {
    title: '步骤1：加载历史异常点',
    content: '从历史数据中提取异常工况点，作为构建异常空间的基础数据。'
  },
  {
    title: '步骤2：生成凸包边界',
    content: '使用 QuickHull 算法对历史异常点生成凸包边界，形成异常识别空间。'
  },
  {
    title: '步骤3：计算当前点距离',
    content: '计算当前车辆热工况向量到凸包边界的最短距离，得到 CTI 值。'
  },
  {
    title: '步骤4：判定结果',
    content: '基于 CTI 值和 SOC 跳变幅度综合判定异常程度和处理路径。'
  }
]

const ctiSections = computed(() => [
  {
    title: '计算公式',
    content: 'CTI = 当前热工况点与凸包边界最近点的直线距离'
  },
  {
    title: '具体计算',
    content: `即：||[${currentVehicle.value?.thmVector.join(',')}] - [0.83,0.65,0.75]||₂ = ${ctiValue.value}`
  },
  {
    title: '判定标准',
    content: 'CTI < 0.01 为高风险，需要启动异常处理路径；0.01-0.05 为风险预警；> 0.05 为正常。'
  }
])

const goToChargingPriority = () => {
  isNavigating.value = true

  setTimeout(() => {
    isNavigating.value = false
    router.push('/priority')
  }, 2000)
}

onMounted(() => {
  if (!currentVehicle.value) {
    router.push('/monitor')
  }
})
</script>
<style scoped>
.chart-container {
  width: 100%;
  height: 500px;
  min-height: 400px;
  position: relative;
}

.chart-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 100%);
  pointer-events: none;
  z-index: 1;
  border-radius: 8px;
}
</style>